<template>
    <div class="video-list-container">
        <!-- 搜索栏 -->
        <el-card shadow="never" class="search-card">
            <el-form :inline="true" :model="queryParams" class="search-form">
                <el-form-item label="视频标题">
                    <el-input v-model="queryParams.title" placeholder="视频标题" clearable />
                </el-form-item>

                <el-form-item label="上传时间">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮和表格 -->
        <el-card shadow="never" class="table-card">
            <template #header>
                <div class="card-header">
                    <span>视频列表</span>
                    <el-button type="primary" @click="handleAdd">上传视频</el-button>
                </div>
            </template>

            <el-table v-loading="loading" :data="videoList" border style="width: 100%">
                <el-table-column type="index" width="50" label="#" />

                <el-table-column prop="cover" label="封面" width="120">
                    <template #default="scope">
                        <el-image style="width: 100px; height: 60px" :src="scope.row.cover" fit="cover"
                            :preview-src-list="[scope.row.cover]" />
                    </template>
                </el-table-column>

                <el-table-column prop="title" label="标题" show-overflow-tooltip />

                <el-table-column prop="duration" label="时长" width="100">
                    <template #default="scope">
                        {{ formatDuration(scope.row.duration) }}
                    </template>
                </el-table-column>

                <el-table-column prop="views" label="播放量" width="100" />

                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '已发布' : '未发布' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="createTime" label="上传时间" width="180" />

                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handlePreview(scope.row)">
                            预览
                        </el-button>
                        <el-button size="small" type="success" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.size"
                    :page-sizes="[10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 视频预览弹窗 -->
        <el-dialog v-model="previewVisible" title="视频预览" width="70%" destroy-on-close>
            <div class="video-container">
                <video v-if="currentVideo.url" :src="currentVideo.url" class="preview-video" controls autoplay></video>
            </div>
            <div class="video-info">
                <h3>{{ currentVideo.title }}</h3>
                <p>{{ currentVideo.description }}</p>
                <div class="video-stats">
                    <span>播放量: {{ currentVideo.views }}</span>
                    <span>上传时间: {{ currentVideo.createTime }}</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVideoList, deleteVideo } from '../../api/video'

const router = useRouter()
const loading = ref(false)
const videoList = ref([])
const total = ref(0)
const dateRange = ref([])
const previewVisible = ref(false)
const currentVideo = ref({})

// 查询参数
const queryParams = reactive({
    page: 1,
    size: 10,
    title: '',
    startDate: '',
    endDate: ''
})

// 监听日期范围选择器
const handleDateRangeChange = () => {
    if (dateRange.value && dateRange.value.length === 2) {
        queryParams.startDate = dateRange.value[0]
        queryParams.endDate = dateRange.value[1]
    } else {
        queryParams.startDate = ''
        queryParams.endDate = ''
    }
}

// 格式化视频时长
const formatDuration = (seconds) => {
    if (!seconds || seconds <= 0) return '00:00'

    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)

    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 获取视频列表
const getList = () => {
    loading.value = true

    // 处理日期范围
    handleDateRangeChange()

    getVideoList(queryParams)
        .then(res => {
            videoList.value = res.data.list || []
            total.value = res.data.total || 0
        })
        .catch(error => {
            console.error('获取视频列表失败:', error)
            ElMessage.error('获取视频列表失败')
        })
        .finally(() => {
            loading.value = false
        })
}

// 搜索
const handleQuery = () => {
    queryParams.page = 1
    getList()
}

// 重置搜索条件
const resetQuery = () => {
    queryParams.title = ''
    dateRange.value = []
    queryParams.startDate = ''
    queryParams.endDate = ''
    handleQuery()
}

// 上传视频
const handleAdd = () => {
    router.push('/video/add')
}

// 编辑视频
const handleEdit = (row) => {
    router.push(`/video/edit/${row.id}`)
}

// 预览视频
const handlePreview = (row) => {
    currentVideo.value = { ...row }
    previewVisible.value = true
}

// 删除视频
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除视频 "${row.title}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        loading.value = true
        deleteVideo(row.id)
            .then(() => {
                ElMessage.success('删除成功')
                getList()
            })
            .catch(error => {
                console.error('删除视频失败:', error)
                ElMessage.error('删除视频失败')
            })
            .finally(() => {
                loading.value = false
            })
    }).catch(() => {
        // 取消删除操作
    })
}

// 处理分页大小变化
const handleSizeChange = (size) => {
    queryParams.size = size
    getList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    queryParams.page = page
    getList()
}

// 初始化
onMounted(() => {
    getList()
})
</script>

<style scoped>
.video-list-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.video-container {
    width: 100%;
    text-align: center;
}

.preview-video {
    max-width: 100%;
    max-height: 500px;
}

.video-info {
    margin-top: 20px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.video-info h3 {
    margin: 0 0 10px 0;
}

.video-info p {
    color: #606266;
    margin: 0 0 10px 0;
}

.video-stats {
    display: flex;
    justify-content: space-between;
    color: #909399;
    font-size: 14px;
}
</style>